<template>
  <div class="wrap">
    <div class="header">
      <div class="left">
        <el-select
          v-model="queryParams.userType"
          placeholder="请选择"
          size="small"
          class="header-select"
          @change="changeOption"
        >
          <el-option :label="$t('common.allStores')" value=""></el-option>
          <el-option :label="$t('other.Multiple users')" :value="1"></el-option>
          <el-option :label="$t('other.Single user')" :value="2"></el-option>
        </el-select>

        <div style="display: inline-block;">
          <el-input size="small" style="width: 200px" v-model="queryParams.keyword" :placeholder="$t('common.Search for store or username')"></el-input>
          <el-button size="small" type="primary" @click="changeOption">{{$t('common.search')}}</el-button>
        </div>
      </div>
      <div class="right">
        <el-button size="small" type="primary" @click="editAdmin()">{{$t('other.Add Operations')}}</el-button>
      </div>

    </div>
    <div class="content">
      <el-table
        v-loading="loading"
        :data="data"
        border
      >
        <el-table-column
          prop="account"
          :label="$t('table.Operational')"
          align="center"
          min-width="120"
        >
          <template v-slot="{row}">
            <el-link @click="jumpAdmin(row)" :underline="false">{{row.account}}</el-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="roleType"
          :label="$t('table.账号角色')"
          align="center"
          min-width="100"
        >
          <template v-slot="{row}">
            {{getRoleTypeName(row.roleType)}}
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          :label="$t('table.备注')"
          align="center"
          width="300"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="warehouse"
          :label="$t('table.warehouse')"
          align="center"
          min-width="100"
        >
          <template slot-scope="{row}">
            <template v-if="row.warehouseId">
              {{ row.warehouseName }}
            </template>
            <template v-else-if="row.flWarehouseId">
              {{ row.flWarehouseName }}
            </template>
            <template v-else>-</template>
          </template>
        </el-table-column>
        <el-table-column
          prop="roles"
          :label="$t('table.功能权限')"
          align="center"
          min-width="150"
        >
          <template slot-scope="{row}">
            <template v-if="row.roles.length === 0">-</template>
            <template v-else>
              {{getRolesStr(row.roles)}}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="effect"
          :label="$t('table.有效店铺/用户数')"
          align="center"
          min-width="150"
        >
          <template slot-scope="{row}">
            {{row.effectAccountNum}}/{{row.effectUserNum}}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          :label="$t('table.createTime3')"
          align="center"
          min-width="100"
        >
        </el-table-column>

        <el-table-column
          :label="$t('table.operate')"
          align="left"
          width="200"
        >
          <template slot-scope="{row}">
            <el-button type="primary" @click="editAdmin(row)">{{ $t('common.edit') }}</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div class="page-wrap">
        <el-pagination
          @current-change="getData"
          :current-page.sync="queryParams.page"
          :page-sizes="[20]"
          :page-size="queryParams.pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      :visible.sync="dialogEdit"
      width="1000px"
      :title="(currentForm.id ? $t('other.Modify Operations') : $t('other.Add Operations'))"
      class="admin-dialog"
    >
      <el-form
        label-width="100px"
        :rules="rules"
        ref="userForm"
        :model="currentForm"
      >
        <el-form-item
          :label="$t('table.user name')"
          prop="account"
        >
          <el-input v-model="currentForm.account"></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('login.password')"
          prop="password"
        >
          <el-input v-model="currentForm.password">
            <template slot="append">
              <el-button @click="createPassword">{{ $t('user.random') }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          :label="$t('table.备注')"
          prop="remark"
        >
          <el-input
            v-model="currentForm.remark"
            type="textarea"
            maxlength="500"
            autosize
            :placeholder="$t('table.选填，仅用于管理端查看、保存更多账号细节')"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('table.账号角色')"
          prop="roleType"
        >
          <template v-if="!currentForm.id">
            <el-radio-group v-model="currentForm.roleType" @change="changeRoleType">
              <el-radio
                v-for="item in roleTypeList"
                :key="item.key"
                :label="item.key"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </template>
          <template v-else>
            {{getRoleTypeName(currentForm.roleType)}}
          </template>

        </el-form-item>
        <el-form-item
          :label="$t('table.warehouse')"
          prop="warehouseId"
          v-if="formIsOperate()"
        >
          <el-radio-group v-model="currentForm.warehouseId">
            <el-radio
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.id"
            >
              {{ item.warehouseName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="国内仓"
          prop="flWarehouseId"
          v-else-if="formIsFlOperate()"
        >
          <el-radio-group v-model="currentForm.flWarehouseId">
            <el-radio
              v-for="item in flWarehouseList"
              :key="item.id"
              :label="item.id"
            >
              {{ item.warehouseName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="$t('table.功能权限')"
          prop="roles"
        >
          <template v-if="formIsOperate()">
            <el-form-item
              :label="$t('table.业务权限（必选，单选）')"
              label-width="200px"
              style="margin-bottom: 0"
            >
              <el-radio-group v-model="currentForm.roleType1" @change="checkRoles">
                <el-radio
                  v-for="item in rolesList1"
                  :label="item.key"
                  :key="item.key"
                  :disabled="!!currentForm.id"
                >
                  {{item.name}}
                  <template v-if="item.key === rolesKey.oneShipping">
                    <el-tooltip class="item" effect="dark" placement="top">
                      <template #content>
                        <div>
                          {{ $t('table.一件代发运营端权限') }}：<br/>
                          {{ $t('route.orderManagement') }} <br/>
                          {{ $t('route.pickingList') }} <br/>
                          {{ $t('route.inventoryManagement') }} <br/>
                          {{ $t('route.setting') }}
                        </div>
                      </template>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </template>
                  <template v-else-if="item.key === rolesKey.middleTransfer">
                    <el-tooltip class="item" effect="dark" placement="top">
                      <template #content>
                        <div>
                          {{ $t('table.中转送仓运营端权限') }}：<br/>
                          {{ $t('route.labelList') }} <br/>
                          {{ $t('route.inventoryManagement') }} <br/>
                          {{ $t('route.shipmentManagement') }} <br/>
                          {{ $t('route.setting') }}
                        </div>
                      </template>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </template>
                  <template v-else-if="item.key === rolesKey.inboundSorting">
                    <el-tooltip class="item" effect="dark" placement="top">
                      <template #content>
                        <div>
                          入库分拣运营端权限：<br/>
                          {{ $t('route.shipmentManagement') }} <br/>
                          货柜管理 <br/>
                          {{ $t('route.inventoryManagement') }}<br/>
                          发货计划
                        </div>
                      </template>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </template>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              :label="$t('table.数据权限（可选，多选）')"
              label-width="200px"
              style="margin-bottom: 0"
            >
              <el-checkbox-group v-model="currentForm.roles">
                <el-checkbox
                  v-for="item in rolesList2"
                  :label="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                  <template v-if="item.key === rolesKey.financeData">
                    <el-tooltip class="item" effect="dark" placement="top">
                      <template #content>
                        <div>
                          {{ $t('table.财务数据运营端权限') }}：<br/>
                          <template v-if="$store.getters.showMenuRemittance">
                            {{ $t('route.RemittanceManagement') }} <br/>
                          </template>
                          {{ $t('route.dataManagement') }} <br/>
                        </div>
                      </template>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </template>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </template>
          <template v-else-if="formIsFinance()">
            <el-checkbox-group v-model="currentForm.roles">
              <el-checkbox
                v-for="item in rolesListFinance"
                :label="item.key"
                :key="item.key"
              >
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
          <template v-else-if="formIsFlOperate()">
            <el-form-item
              :label="$t('table.业务权限（必选，单选）')"
              label-width="200px"
              style="margin-bottom: 0"
            >
              <el-checkbox-group v-model="currentForm.roles" :disabled="true">
                <el-checkbox :label="ROLE_FIRST_LEG()">头程管理</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
              :label="$t('table.数据权限（可选，多选）')"
              label-width="200px"
              style="margin-bottom: 0"
            >
              <el-checkbox-group v-model="currentForm.roles">
                <el-checkbox
                  v-for="item in rolesListFlOperate"
                  :label="item.key"
                  :key="item.key"
                >
                  {{ item.name }}
                  <template v-if="item.key === rolesKey.financeData">
                    <el-tooltip class="item" effect="dark" placement="top">
                      <template #content>
                        <div>
                          {{ $t('table.财务数据运营端权限') }}：<br/>
                          <template v-if="$store.getters.showMenuRemittance">
                            {{ $t('route.RemittanceManagement') }} <br/>
                          </template>
                          {{ $t('route.dataManagement') }} <br/>
                        </div>
                      </template>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </template>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>


          </template>


        </el-form-item>

        <template v-if="formIsOperate()">
          <el-form-item
            :label="$t('table.店铺权限')"
            prop="accountAuth"
          >
            <el-tabs v-model="currentForm.handleModel" @tab-click="handleClick" style="line-height: 32px" :before-leave="changeTabs">
              <el-tab-pane :label="$t('table.店铺绑定')" name="account"></el-tab-pane>
              <el-tab-pane :label="$t('table.用户转移')" name="user"></el-tab-pane>
            </el-tabs>
            <template v-if="currentForm.handleModel === 'account'">
              <div class="font-red font-bold">
                {{$t('同一业务权限中，1个店铺只能绑定在1个运营账号下，以下仅列出未被任何运营绑定的店铺（有效用户）')}}
              </div>
              <template v-if="formAccountList.length > 0">
                <div class="font-grey f13">
                  {{ $t('如需将已绑定的店铺换绑到其他运营账号下，请取消勾选，点击「确认」后前往对应运营账号编辑页面继续操作') }}
                </div>
                <div
                  class="account-auth-content"
                  v-for="item in formAccountList"
                  :key="item.userId"
                >
                  <div class="user-account">{{ item.account }}</div>
                  <div class="account-list">
                    <el-checkbox class="account-checkbox" :value="isAllAccount(item.userId)" @change="chooseAllAccount(item.userId)">全选</el-checkbox>
                    <el-checkbox
                      class="account-checkbox"
                      v-for="account in item.userAccountList"
                      :label="account.ogAccountId"
                      :key="account.ogAccountId"
                      v-model="currentForm.accountAuth"
                      @change="testAccount"
                    >
                      <el-tooltip class="item" effect="dark" :content="account.showName" placement="top">
                        <span class="account-label">{{ truncate(account.showName, 10) }}</span>
                      </el-tooltip>
                    </el-checkbox>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="font-grey f13">
                  {{$t('暂无可绑定的店铺，请前往其他运营账号下取消绑定后再返回操作')}}
                </div>
              </template>

            </template>
            <template v-else-if="currentForm.handleModel === 'user'">
              <div class="font-red">
                {{$t('若用户账号由A运营账号创建，则该用户后续授权的所有店铺将自动绑定在A运营账号下')}}
              </div>
              <div class="font-red">
                {{ $t('使用“转移”功能后，当前用户中现有所有以及后续授权的店铺，将自动绑定到当前运营账号下面（独立的单价设置将保留）') }}
              </div>

              <div class="font-grey f13">
                {{$t('直接选中下方需要转移到当前运营账号下的用户名，然后点击下方的「确认」按钮即可')}}
              </div>
              <el-checkbox-group v-model="currentForm.userAuth">
                <el-checkbox
                  class="account-checkbox"
                  v-for="user in formUserList"
                  :label="user.userId"
                  :key="user.userId"
                  :disabled="user.disable"
                >
                  {{user.account}}
                  <template v-if="user.adminAccount">
                    ({{user.adminAccount}})
                  </template>
                </el-checkbox>
              </el-checkbox-group>
            </template>

          </el-form-item>
        </template>
        <template v-else-if="formIsFinance()">
          <el-form-item
            :label="$t('table.店铺权限')"
            prop="userAuth"
          >

            <el-checkbox v-model="currentForm.allUser" @change="chooseAllUser">{{ $t('common.allUsers') }}</el-checkbox>

            <div>
              <div
                v-for="user in userAccountList"
                :key="user.id"
              >
                <el-checkbox :label="user.id" :disabled="currentForm.allUser" @change="chooseUserAllAccount(user.id)" :value="currentForm.userAuth.indexOf(user.id) !== -1">{{$t('other.user all stores',{name:user.account})}}</el-checkbox>
                <el-checkbox
                  :disabled="currentForm.userAuth.indexOf(user.id) !== -1 || currentForm.allUser"
                  v-for="item in user.accountList"
                  :key="item.id"
                  :label="item.id"
                  v-model="currentForm.accountAuth"
                  @change="chooseAccount"
                >
                  {{item.showName}}({{user.account}})
                </el-checkbox>
              </div>
            </div>

          </el-form-item>
        </template>


        <el-form-item
          :label="$t('table.status')"
          prop="status"
        >
          <el-radio-group v-model="currentForm.status">
            <el-radio :label="1">{{$t('user.In cooperation')}}</el-radio>
            <el-radio :label="0">{{$t('user.Stop cooperation')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="submitForm()" :loading="dialogLoading">{{ $t('common.save') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


  </div>
</template>

<script>
import {deepCopy, generateRandomString} from "@/utils";
import request from "@/utils/request";
import userAccountOptions from "@/views/order/mixin/userAccountOptions";
import {editAdmin, getAdminList, getAdminLoginWithKey, getAllAuthAccount, saveAdmin} from "@/api/admin";
import {getFlWarehouseList, getWarehouseList} from "@/api/warehouse";
import user from "@/store/modules/user";
import {
  getRoleName, getRoleTypeName,
  ROLE_DATA_MANAGE,
  ROLE_FINANCE,
  ROLE_FINANCE_DATA, ROLE_FIRST_LEG, ROLE_FL_OPERATE, ROLE_INBOUND_SORTING,
  ROLE_MIDDLE_TRANSFER,
  ROLE_ONE_SHIPPING,
  ROLE_OPERATE, ROLE_REMITTANCE_MANAGE, ROLE_SHIPPING_PLAN, ROLE_STOCK_MANAGE, ROLE_USER_MANAGE
} from "@/utils/admin";
import {MessageBox} from "element-ui";
import {getUserLoginWithKey} from "@/api/user";


const rolesKey = {
  oneShipping: ROLE_ONE_SHIPPING, // 一件代发
  middleTransfer: ROLE_MIDDLE_TRANSFER, // 中转送仓
  firstLeg: ROLE_FIRST_LEG, // 头程管理
  inboundSorting: ROLE_INBOUND_SORTING, // 入库分拣
  financeData: ROLE_FINANCE_DATA, // 财务数据
  dataManage: ROLE_DATA_MANAGE, // 数据管理
  remittanceManage: ROLE_REMITTANCE_MANAGE, // 汇款管理
  userManage: ROLE_USER_MANAGE, // 用户管理
  shippingPlan: ROLE_SHIPPING_PLAN, // 发货计划
  stockManage: ROLE_STOCK_MANAGE, // 库存管理
}
export default {
  name: "adminList",
  mixins: [userAccountOptions],
  computed: {
    rolesList1(){
      return this.roleList.filter(item => item.type === 1 && item.isOperate)
    },
    rolesList2(){
      return this.roleList.filter(item => {
        if(this.currentForm.roleType1 === ROLE_INBOUND_SORTING){
          if(item.key === ROLE_SHIPPING_PLAN){
            return false
          }
        }
        return item.type === 2 && item.isOperate
      })
    },
    rolesListFlOperate(){
      return this.roleList.filter(item => item.type === 2 && item.isFlOperate)
    },
    rolesListFinance(){
      return this.roleList.filter(item=> item.isFinance)
    },
    formAccountList(){
      let oneShippingIndex = this.currentForm.roles.indexOf(rolesKey.oneShipping)
      let middleTransferIndex = this.currentForm.roles.indexOf(rolesKey.middleTransfer)
      let inboundSortingIndex = this.currentForm.roles.indexOf(rolesKey.inboundSorting)

      // let isOneShipping = false
      // if (this.currentForm.roles.includes('oneShipping')) {
      //   isOneShipping = true
      // }
      // console.log(this.allUserAccount)

      const arr = []
      this.allUserAccount.filter(item => item.effect)
        .map(item=>{
          const obj = deepCopy(item)
          obj.userAccountList = obj.userAccountList.filter(accountItem=>{
            if(oneShippingIndex !== -1){
              return accountItem.oneShippingAdminId === 0 || accountItem.oneShippingAdminId === this.currentForm.id
            }else if(middleTransferIndex !== -1){
              return (accountItem.middleTransferAdminId === 0 && accountItem.is_packet === false) || (accountItem.middleTransferAdminId === this.currentForm.id && accountItem.is_packet === false)
            }else if(inboundSortingIndex !== -1){
              return accountItem.inboundSortingAdminId === 0 || accountItem.inboundSortingAdminId === this.currentForm.id
            }
            return false
          })
          if(obj.userAccountList.length > 0){
            arr.push(obj)
          }
        })
      return arr;
    },
    formUserList(){
      let oneShippingIndex = this.currentForm.roles.indexOf(rolesKey.oneShipping)
      let middleTransferIndex = this.currentForm.roles.indexOf(rolesKey.middleTransfer)
      let inboundSortingIndex = this.currentForm.roles.indexOf(rolesKey.inboundSorting)

      if(!this.currentForm.roleType1){
        return []
      }

      return this.allUserAccount.map(item=>{
        item.adminAccount = '';
        let currentAdminId = 0
        if(oneShippingIndex !== -1){
          item.adminAccount = item.oneShippingAdminAccount
          currentAdminId = item.oneShippingAdminId
        }else if(middleTransferIndex !== -1){
          item.adminAccount = item.middleTransferAdminAccount
          currentAdminId = item.middleTransferAdminId
        }else if(inboundSortingIndex !== -1){
          item.adminAccount = item.inboundSortingAdminAccount
          currentAdminId = item.inboundSortingAdminId
        }
        item.disable = this.currentForm.id !== 0 && this.currentForm.id === currentAdminId
        return item;
      })
    },
  },
  data(){
    // 校验用户名是否有重复的
    const checkAccount = (rule, value, callback) => {
      request({
        url: '/admin/checkAdminAccount',
        method: 'get',
        params: this.currentForm,
        handleError: true,
      }).then(res=>{
        if(res.error !== 0){
          callback(new Error(res.message));
        }else{
          callback();
        }
      })
    };

    const roleTypeList = [
      {
        name: this.$t('头程运营'),
        key: ROLE_FL_OPERATE, // 唯一的key
      },
      {
        name: this.$t('尾程运营'),
        key: ROLE_OPERATE, // 唯一的key
      },
      {
        name: this.$t('table.财务'),
        key: ROLE_FINANCE, // 唯一的key
      },
    ]; // 账号角色

    const roleList = [
      {
        name: this.$t('shipment.oneStock'),
        key: rolesKey.oneShipping,
        type: 1, // 用于区分业务权限还是数据权限 1：业务权限 2：数据权限
        isFinance: false, // 用于区分是不是财务权限
        isOperate: true, // 用于区分是不是运营权限
        isFlOperate: false, // 用于区分是不是头程运营权限
      }, // 一件代发
      {
        name: this.$t('shipment.middleWarehouse'),
        key: rolesKey.middleTransfer,
        type: 1,
        isFinance: false,
        isOperate: true,
        isFlOperate: false,
      }, // 中转送仓
      {
        name: '头程管理',
        key: rolesKey.firstLeg,
        type: 1,
        isFinance: false,
        isOperate: false,
        isFlOperate: true,
      }, // 头程管理
      {
        name: '入库分拣',
        key: rolesKey.inboundSorting,
        type: 1,
        isFinance: false,
        isOperate: true,
        isFlOperate: false,
      }, //
      {
        name: this.$t('data.财务数据'),
        key: rolesKey.financeData,
        type: 2,
        isFinance: false,
        isOperate: true,
        isFlOperate: true,
      }, // 财务数据
      {
        name: this.$t('route.dataManagement'),
        key: rolesKey.dataManage,
        type: 2,
        isFinance: true,
        isOperate: false,
        isFlOperate: false,
      }, // 数据管理
      {
        name: this.$t('route.RemittanceManagement'),
        key: rolesKey.remittanceManage,
        type: 2,
        isFinance: true,
        isOperate: false,
        isFlOperate: false,
      }, // 汇款管理
      {
        name: this.$t('data.用户管理'),
        key: rolesKey.userManage,
        type: 2,
        isFinance: true,
        isOperate: true,
        isFlOperate: true,
      }, // 用户管理
      {
        name: '发货计划',
        key: rolesKey.shippingPlan,
        type: 2,
        isFinance: false,
        isOperate: true,
        isFlOperate: false,
      }, // 发货计划
      {
        name: '库存管理',
        key: rolesKey.stockManage,
        type: 2,
        isFinance: false,
        isOperate: false,
        isFlOperate: true,
      }, // 库存管理
    ]; // 权限功能

    if(!this.$store.getters.showMenuRemittance){
      const index = roleList.findIndex(item=> item.key === rolesKey.remittanceManage)
      roleList.splice(index, 1)
    }

    return {
      queryParams:{
        page: 1,
        pageSize: 20,
        userType: '',
        keyword: '',
      },
      data:[],
      loading: false,
      total: 0,
      currentForm: {
        id: 0,
        account: '',
        name: '',
        password: '',
        userAuth: [],
        accountAuth: [],
        status: 1,
        allUser: false,
        remark: '', // 备注
        roleType: ROLE_FL_OPERATE, // 角色类型
        warehouseId: '', // 仓库
        roles: [], // 权限
        handleModel: 'account', // 操作类型
        flWarehouseId: 0, // 国内仓
        roleType1: '',
      },
      defaultForm: null,
      isEdit: false, // 用于判断添加还是编辑
      dialogEdit: false,
      dialogLoading: false,
      rules:{
        account: [
          { required: true, message: this.$t('common.pleaseFillIn'), trigger: 'blur'},
          { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_-]+$/ , message: this.$t('user.userValid3'),trigger: 'blur' },
          { validator:checkAccount, trigger: 'blur' },
        ],
        password: [
          {required: true, message: this.$t('user.userValid4'), trigger: ['blur', 'change'],min:6}
        ],
        roleType: [
          {required: true, message: this.$t('common.请选择'), trigger: 'change'},
        ],
        warehouseId: [
          {required: true, message: this.$t('common.请选择'), trigger: 'change'}
        ],
        flWarehouseId: [
          {required: true, message: this.$t('common.请选择'), trigger: 'change'}
        ],

      },
      warehouseList: [], // 获取所有仓库
      flWarehouseList: [], // 国内仓
      roleTypeList: roleTypeList,
      roleList: roleList,
      financeRoleList: [

      ],
      rolesKey,
      allUserAccount: [],
      currentRow: null,
    }
  },
  created() {
    this.defaultForm = deepCopy(this.currentForm)
    this.getData()
    this.getWarehouse() // 获取仓库
    this.getFlWarehouse()
    this.getAllAuthAccount()
  },
  methods:{
    ROLE_FIRST_LEG() {
      return ROLE_FIRST_LEG
    },
    getRoleTypeName,
    truncate(text, length) {
      if (text.length > length) {
        return text.substring(0, length) + '...';
      }
      return text;
    },
    jumpAdmin(row){
      getAdminLoginWithKey(row.id)
        .then(res=>{
          window.open(res.data.url,'_blank')
        })
    },
    getData(){
      this.loading = true
      getAdminList(this.queryParams)
        .then(res=>{
          this.loading = false
          this.data = deepCopy(res.data)
          this.total = res.info.total
        })
    },
    getAllAuthAccount(){
      this.authLoading = true
      getAllAuthAccount()
        .then(res=>{
          this.authLoading = false
          this.allUserAccount = res.data
        })
    },
    // 编辑运营
    editAdmin(row = null){
      // console.log(row)
      this.isEdit = !!row
      this.dialogEdit = true
      this.currentRow = null
      this.currentForm.roleType1 = '';
      if(row){
        this.currentRow = deepCopy(row)
        // this.currentForm = deepCopy(row)
        this.currentForm.id = row.id
        this.currentForm.account = row.account
        this.currentForm.name = row.name
        this.currentForm.password = row.password
        this.currentForm.status = row.status
        this.currentForm.userAuth = [];
        this.currentForm.accountAuth = [];
        this.currentForm.allUser = false
        if(row.authType === 1){ // 是否全权限
          this.currentForm.allUser = true;
        }
        this.currentForm.roleType = row.roleType
        this.currentForm.warehouseId = row.warehouseId
        this.currentForm.flWarehouseId = row.flWarehouseId
        this.currentForm.roles = row.roles
        this.currentForm.handleModel = 'account'
        this.currentForm.remark = row.remark
        const arr = this.roleList.filter(item=> item.type === 1).map(item=> item.key)
        this.currentForm.roles.some(item=>{
          if(arr.indexOf(item) !== -1){
            this.currentForm.roleType1 = item
            return true
          }
        })
        this.setCurrentFormAuth()

      }else{
        this.currentForm = deepCopy(this.defaultForm)
        if(this.warehouseList.length >= 1){
          this.currentForm.warehouseId = this.warehouseList[0].id
        }
        this.currentForm.roles = [ROLE_FIRST_LEG]
        // this.currentForm.roleType1 = this.rolesList1[0].key
      }
    },
    setCurrentFormAuth(){
      if(!this.currentRow){
        this.currentForm.userAuth = [];
        this.currentForm.accountAuth = [];
        return
      }
      let oneShippingIndex = this.currentForm.roles.indexOf(rolesKey.oneShipping)
      let middleTransferIndex = this.currentForm.roles.indexOf(rolesKey.middleTransfer)
      let inboundSortingIndex = this.currentForm.roles.indexOf(rolesKey.inboundSorting)
      this.currentForm.userAuth = this.allUserAccount.filter(item=>{
        if(oneShippingIndex !== -1 && item.oneShippingAdminId === this.currentForm.id){
          return true
        }
        if(middleTransferIndex !== -1 && item.middleTransferAdminId === this.currentForm.id){
          return true
        }
        if(inboundSortingIndex !== -1 && item.inboundSortingAdminId === this.currentForm.id){
          return true
        }
        return false
      }).map(item=>{
        return item.userId
      })
      const arr = [];
      this.formAccountList.forEach(item=>{
        item.userAccountList.forEach(accountItem=>{
          if(oneShippingIndex !== -1 && accountItem.oneShippingAdminId === this.currentForm.id){
            arr.push(accountItem.ogAccountId)
          }
          if(middleTransferIndex !== -1 && accountItem.middleTransferAdminId === this.currentForm.id){
            arr.push(accountItem.ogAccountId)
          }
          if(inboundSortingIndex !== -1 && accountItem.inboundSortingAdminId === this.currentForm.id){
            arr.push(accountItem.ogAccountId)
          }
        })
      })
      this.currentForm.accountAuth = arr
      this.currentRow.userAuth = deepCopy(this.currentForm.userAuth);
      this.currentRow.accountAuth = deepCopy(this.currentForm.accountAuth);
    },
    // 保存
    submitForm(){
      this.$refs.userForm.validate(valid => {
        if(valid){

          if(this.currentForm.roles.length === 0){
            this.$errorMessage('请至少选择一个权限')
            return;
          }
          // 运营
          if(this.currentForm.roleType === 'operate'){
            if(!this.currentForm.roleType1){
              this.$errorMessage('请至少选择一个业务权限');
              return;
            }
          }


          const postData = deepCopy(this.currentForm)
          this.dialogLoading = true
          if(postData.id){
            editAdmin(postData)
              .then(res=>{
                this.dialogLoading = false
                if(res.error === 0){
                  this.dialogEdit = false
                  this.$successMessage(res.message)
                  this.getAllAuthAccount()
                  this.getData()
                  this.$store.dispatch('user/getInfo');
                }else{
                  this.$errorMessage(res.message)
                }
              })
          }else{
            saveAdmin(postData)
              .then(res=>{
                this.dialogLoading = false
                if(res.error === 0){
                  this.dialogEdit = false
                  this.$successMessage(res.message)
                  this.getAllAuthAccount()
                  this.getData()
                  this.$store.dispatch('user/getInfo');
                }else{
                  this.$errorMessage(res.message)
                }
              })
          }
        }
      })
    },
    // 店铺权限
    checkGroup(){
      if(this.currentForm.userAuth.indexOf('*') !== -1){
        this.currentForm.userAuth = ['*']
      }
    },
    // 搜索
    changeOption(){
      this.queryParams.page = 1;
      this.getData()
    },
    // 选择所有用户
    chooseAllUser(){
      if(this.currentForm.allUser){
        this.currentForm.userAuth = []
        this.currentForm.accountAuth = []
      }
    },
    chooseUserAllAccount(userId){
      const userIndex = this.currentForm.userAuth.indexOf(userId);
      if(userIndex !== -1){
        this.currentForm.userAuth.splice(userIndex,1)
      }else{
        this.currentForm.userAuth.push(userId)
        this.userAccountList.some(item=>{
          if(item.id === userId){
            item.accountList.forEach(accountItem=>{

              const index = this.currentForm.accountAuth.findIndex(accountId => accountId === accountItem.id)
              if(index !== -1){
                this.currentForm.accountAuth.splice(index,1)
              }
            })
            return true
          }
        })
      }
    },
    chooseAccount(){

    },
    getWarehouse(){
      getWarehouseList({
        page: 1,
        pageSize: 100,
      })
        .then(res=>{
          this.warehouseList = res.data
          if(this.warehouseList.length >= 1){
            this.defaultForm.warehouseId = this.warehouseList[0].id
          }
        })
    },
    getFlWarehouse(){
      getFlWarehouseList({
        page: 1,
        pageSize: 100,
      })
        .then(res=>{
          this.flWarehouseList = res.data
          if(this.flWarehouseList.length >= 1){
            this.defaultForm.flWarehouseId = this.flWarehouseList[0].id
          }
        })
    },
    // 一件代发和中转送仓、入库分拣只能选一个
    checkRoles(){
      const key1 = rolesKey.oneShipping
      const key2 = rolesKey.middleTransfer
      const key3 = rolesKey.inboundSorting
      const arr = [key1,key2,key3]
      arr.forEach(key=>{
        const index = this.currentForm.roles.indexOf(key)
        if(index !== -1){
          this.currentForm.roles.splice(index,1)
        }
      })
      if(this.currentForm.roleType1){
        this.currentForm.roles.push(this.currentForm.roleType1)
      }
    },
    // 表单是不是运营
    formIsOperate(){
      return this.currentForm.roleType === 'operate'
    },
    // 是不是财务
    formIsFinance(){
      return this.currentForm.roleType === ROLE_FINANCE;
    },
    // 表单是不是头程运营
    formIsFlOperate(){
      return this.currentForm.roleType === ROLE_FL_OPERATE;
    },
    // 切换
    handleClick(){
      console.log(this.currentForm)
    },
    testAccount(){
      // console.log(this.currentForm.accountAuth)
    },
    isAllAccount(userId){
      const userAccount = this.formAccountList.find(item => item.userId === userId)
      return userAccount.userAccountList.every(item=>{
        return this.currentForm.accountAuth.indexOf(item.ogAccountId) !== -1
      })
    },
    chooseAllAccount(userId){
      const flag = this.isAllAccount(userId)
      const userAccount = this.formAccountList.find(item => item.userId === userId)
      userAccount.userAccountList.forEach(item=>{
        const index = this.currentForm.accountAuth.indexOf(item.ogAccountId)
        if(flag){
          if(index !== -1){
            this.currentForm.accountAuth.splice(index, 1)
          }
        }else{
          if(index === -1){
            this.currentForm.accountAuth.push(item.ogAccountId)
          }
        }
      })
    },
    // 改变角色权限
    changeRoleType(){
      if(this.currentForm.roleType === 'finance'){
        this.currentForm.roles = this.rolesListFinance.map(item=>{
          return item.key
        })
      }else if(this.currentForm.roleType === ROLE_FL_OPERATE){
        this.currentForm.roles = [ROLE_FIRST_LEG]
      } else{
        this.currentForm.roles = []
      }
    },
    // 随机密码
    createPassword(){
      this.currentForm.password = generateRandomString()
    },
    getRolesStr(roles){
      const arr = roles.map(item=>{
        // 根据权限获取对应的翻译名称
        return getRoleName(item)
      })
      return arr.join('、')
    },
    changeTabs(beforeName,afterName){
      return new Promise((resolve, reject)=>{
        if(!this.currentRow){
          if(this.currentForm.accountAuth.length > 0 || this.currentForm.userAuth.length > 0){
            MessageBox.confirm('确认切换后，当前已修改的所有店铺权限信息都不会被保留', '切换店铺权限？',{}).then(() => {
              this.setCurrentFormAuth()
              resolve();
            }).catch(() => {
              reject();
            });
          }else {
            return resolve();
          }
        }else{
          let flag = false
          if(afterName === 'account' && this.currentForm.accountAuth.toString() !== this.currentRow.accountAuth.toString()  ){
            flag = true
          }
          if(afterName === 'user' && this.currentForm.userAuth.toString() !== this.currentRow.userAuth.toString()){
            flag = true
          }
          if(flag){
            MessageBox.confirm('确认切换后，当前已修改的所有店铺权限信息都不会被保留', '切换店铺权限？',{}).then(() => {
              this.setCurrentFormAuth()
              resolve();
            }).catch(() => {
              reject();
            });
          }else{
            resolve();
          }


        }

      })
    }
  }
}
</script>

<style>
.account-checkbox .account-label {
  display: inline-block;
  max-width: 150px; /* 你可以根据需要调整这个宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}
</style>
<style>
.admin-dialog{
  .el-tabs__item{
    height: 40px;
    line-height: 32px;
  }
}

</style>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header{
    display: flex;
    justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }
}
.header-select{
  margin-right: 20px;
}
.admin-dialog{
  .account-auth-content{
    display: flex;
    .user-account{
      min-width: 100px;
    }
    .account-list{
      .account-checkbox{
        width: 120px;
      }
    }
  }
}
</style>
